package com.xuedakun.xasdk.net.volley;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.xuedakun.xasdk.net.HttpUtils;
import com.xuedakun.xasdk.net.JsonUtils;

/**
 * Created by xuedakun on 2017/6/3 22:51
 * volley 请求的回调
 *
 * @version : v1.0
 * @project : xasdk
 * @Email : dakun611@Gmail.com
 */

public abstract class VolleyCallback<R extends BaseResult> implements Response.Listener<String>, Response.ErrorListener {

    protected RequestCallback<R> requestCallback;

    protected Class<R> clazz;

    protected R result;

    public VolleyCallback(Class<R> clazz) {
        this.clazz = clazz;
    }

    void setRequestCallback(RequestCallback<R> requestCallback) {
        this.requestCallback = requestCallback;
    }

    @Override
    public void onResponse(String response) {
        result = JsonUtils.fromJsonString(response, clazz);
        result.setRequestCode(HttpUtils.HTTP_CODE_OK);
        result.setJson(response);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        result = newResultInstance();
        result.setRequestCode(error.networkResponse.statusCode);
    }

    /**
     * 实例一个R
     * @return
     */
    protected R newResultInstance() {
        R data = null;
        try {
            data = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return data;
    }
}
